package shttp

import (
	"log"
	"net/http"
)

type Controller struct {
	Path                string
	ControllerInterface ControllerInterface
}

var handles = make([]Controller, 0)
var routes = make([]*Route, 0)

// 注册控制器
func RegisterController(path string, controller interface{}) {
	controllerInterface, ok := (controller).(ControllerInterface)
	if !ok {
		log.Println(path, "controller must implement ControllerInterface")
		return
	}
	handles = append(handles, Controller{
		Path:                path,
		ControllerInterface: controllerInterface,
	})
}

// 注册所有控制器的路由
func registerRoutes(mux *http.ServeMux) {
	for _, handle := range handles {
		// path去掉最后一个/
		if handle.Path != "" && handle.Path[len(handle.Path)-1] == '/' {
			handle.Path = handle.Path[:len(handle.Path)-1]
		}
		routes := handle.ControllerInterface.GetHttpHandlers()
		for _, route := range routes {
			if route.Path == "" {
				continue
			}
			if route.Path[0] != '/' {
				route.Path = "/" + route.Path
			}
			routepath := handle.Path + route.Path
			mux.HandleFunc(routepath, route.HandlerFunc)
			routes = append(routes, route)
		}
	}
}

// 注册控制器的路由
func RegisterHandlerFunc(path, method, name string, handler func(w http.ResponseWriter, r *http.Request)) {
	routes = append(routes, &Route{
		Path:        path,
		Method:      method,
		Name:        name,
		HandlerFunc: handler,
	})
}

type Shttp struct {
	Address string
	Mux     *http.ServeMux
}

func NewShttp(address string) *Shttp {
	return &Shttp{
		Address: address,
		Mux:     http.NewServeMux(),
	}
}

func (s *Shttp) Start() {
	registerRoutes(s.Mux)
	log.Fatal(http.ListenAndServe(s.Address, s.Mux))
	log.Fatal(http.ListenAndServe(s.Address, s.Mux))
}
